package com.cxb.receiver;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Environment;
import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.cxb.R;
import com.cxb.manager.PhoneManager;
import com.cxb.manager.PhoneManager.PhoneState;
import com.cxb.manager.PowerOffState;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Constants;
import com.cxb.utils.Debug;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.Tts;

public class KeyDownReceiver extends BroadcastReceiver {

	private SharedPreferencesUtils sharedPreferencesUtils = null;
	private Handler mHandler;

	public boolean isAtHome(Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.addCategory(Intent.CATEGORY_HOME);
		PackageManager pm = context.getPackageManager();
		List<ResolveInfo> list = pm.queryIntentActivities(intent,
				PackageManager.GET_ACTIVITIES);
		for (ResolveInfo resolveInfo : list) {
			if (cn.getClassName().equals(resolveInfo.activityInfo.name)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onReceive(final Context context, Intent intent) {
		if (getCurrentActivity(context).contains("com.cxb.SetupWizardActivity")) {
			return;
		}

		if (getCurrentPkgName(context).contains("com.zzx.factorytest")) {
			return;
		}
		if (PowerOffState.isPowerOffing) {
			Log.e("test", "shutdown ing  do not deal keyevent");
			return;
		}

		PhoneManager phoneManager = new PhoneManager(context);

		if (intent.getAction().equals(
				Constants.IntentData.ACTION_RECEIVE_KEYDOWN_INTENT)) {
			sharedPreferencesUtils = new SharedPreferencesUtils(context);

			int keyCode = intent.getIntExtra(
					Constants.IntentData.EXTRA_KEY_CODE, -1);
			if (keyCode == -1) {

				keyCode = intent.getIntExtra("EXTRA_KEY_CODE", -1);
			}
			Log.e("test", "keyCode=" + keyCode + " isAtHome="
					+ isAtHome(context));
			if (keyCode == 3) {// HOME键

				// if (isAtHome(context)&&!ScreenMonitor.isShowing) {
				// context.sendBroadcast(new Intent(
				// ScreenMonitor.ACTION_SCREEN_MONITOR_SHOW));
				// }else if(ScreenMonitor.isShowing){
				//
				// context.sendBroadcast(new Intent(
				// ScreenMonitor.ACTION_SCREEN_MONITOR_DIMISS));
				// }

				context.sendBroadcast(new Intent("preview_window_off"));
			}
			if (keyCode == Constants.HareWareKeyCode.KEYCODE_HOME) {// HOME键

				// if (isAtHome(context)&&!ScreenMonitor.isShowing) {
				// context.sendBroadcast(new Intent(
				// ScreenMonitor.ACTION_SCREEN_MONITOR_SHOW));
				// }else if(ScreenMonitor.isShowing){
				//
				// context.sendBroadcast(new Intent(
				// ScreenMonitor.ACTION_SCREEN_MONITOR_DIMISS));
				// }

				context.sendBroadcast(new Intent("preview_window_off"));
			} else {
				if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
					return;
				}
	
			}
			if (keyCode == Constants.HareWareKeyCode.KEYCODE_ONESTONE) {// 一键通
				// if (!DebugSwitch.ISPINGAN) {

				if (!CommonUtils.isServiceRunning(context,
						"com.leader.recorder.PreviewService")) {
					Toast.makeText(context, "行车记录仪启动中,请稍等...", 0).show();
				}



			} else if (keyCode == Constants.HareWareKeyCode.KEYCODE_ONE_KEY_RESCUE) {// 一键救援
				SharedPreferencesUtils sp = new SharedPreferencesUtils(context);
				if (sp.getSOSNumber() != null
						&& sp.getSOSNumber().length() >= 7) {
					if (PhoneManager.getCallState() == PhoneState.DIALING
							|| PhoneManager.getCallState() == PhoneState.ACTIVE) {
						phoneManager.endCall();
					} else {
						phoneManager
								.call(sharedPreferencesUtils.getSOSNumber());
					}
				}
			} else if (keyCode == Constants.HareWareKeyCode.KEYCODE_NAVI) {// 导航

				if (mHandler == null) {
					mHandler = new Handler();
				}

				if (Environment.MEDIA_MOUNTED.equals(Environment
						.getExternalStorageState())) {

					Intent intent2 = new Intent();
					intent2.setAction(Intent.ACTION_MAIN);
					intent2.addCategory(Intent.CATEGORY_LAUNCHER);
					intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

					intent2.setClassName("com.autonavi.xmgd.navigator",
							"com.autonavi.xmgd.navigator.Warn");
					context.startActivity(intent2);
					mHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							Intent iRecorder = new Intent();
							iRecorder.setAction("preview_window_off");
							context.sendBroadcast(iRecorder);

						}
					}, 1000);

				} else {
					if (CommonUtils.isUSBMass()) {
						Toast.makeText(context,
								R.string.usb_mass_cannot_use_map_navi, 0)
								.show();
						Tts.speak(context
								.getString(R.string.usb_mass_cannot_use_map_navi));

					} else {

						Toast.makeText(context, R.string.init_map, 0).show();
						Tts.speak(context.getString(R.string.init_map));
						mHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								Debug.printf("test", "task setUpMapBackGround");
								if (Environment.MEDIA_MOUNTED
										.equals(Environment
												.getExternalStorageState())) {
									Intent intent2 = new Intent();
									intent2.setAction(Intent.ACTION_MAIN);
									intent2.addCategory(Intent.CATEGORY_LAUNCHER);
									intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
											| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

									intent2.setClassName(
											"com.autonavi.xmgd.navigator",
											"com.autonavi.xmgd.navigator.Warn");
									context.startActivity(intent2);
									mHandler.postDelayed(new Runnable() {

										@Override
										public void run() {
											Intent iRecorder = new Intent();
											iRecorder
													.setAction("preview_window_off");
											context.sendBroadcast(iRecorder);

										}
									}, 1000);
								} else {
									mHandler.postDelayed(this, 1000);
								}
							}
						}, 1000);

					}
				}
			} else if (keyCode == Constants.HareWareKeyCode.KEYCODE_RECORDER) {// 保存录像
				Intent intentRecord = new Intent();
				intentRecord.setAction("lock_record_file");
				context.sendBroadcast(intentRecord);
			} else if (keyCode == Constants.HareWareKeyCode.KEYCODE_WENWEN) {
				ActivityManager am = (ActivityManager) context
						.getSystemService(Context.ACTIVITY_SERVICE);
				ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
				if (!"com.mobvoi.incar".equals(cn.getPackageName())) {
					// Intent i = new Intent();
					// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					// | Intent.FLAG_ACTIVITY_CLEAR_TASK);
					//
					// i.setClassName("com.mobvoi.incar",
					// "com.mobvoi.incar.ui.activity.SpeechActivity");
					// context.startActivity(i);
				}
			}
			// else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
			// || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			// AudioManager am = (AudioManager) context
			// .getSystemService(Context.AUDIO_SERVICE);
			// am.get
			//
			// }
		}
	}

	public String getCurrentActivity(Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		Log.e("test", "pkg:" + cn.getPackageName());
		Log.e("test", "cls:" + cn.getClassName());
		return cn.getClassName();
	}

	public String getCurrentPkgName(Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		Log.e("test", "pkg:" + cn.getPackageName());
		Log.e("test", "cls:" + cn.getClassName());
		return cn.getPackageName();
	}

	class MyPhoneStateListener extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:

				break;
			case TelephonyManager.CALL_STATE_RINGING:
				PhoneManager.setConectingPhoneNumber(incomingNumber);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:

			default:
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}
	}

	public int getMainPageTaskId(Context context) {
		final ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runingAppList = activityManager
				.getRunningTasks(10);
		for (RunningTaskInfo runningTaskInfo : runingAppList) {
			if (runningTaskInfo.baseActivity.getPackageName().equals("com.cxb")) {
				return runningTaskInfo.id;
			}
		}

		return -1;
	}

	public boolean isMaininHead(Context context) {
		final ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runingAppList = activityManager
				.getRunningTasks(1);
		for (RunningTaskInfo runningTaskInfo : runingAppList) {
			if (runningTaskInfo.baseActivity.getPackageName().equals("com.cxb")) {
				return true;
			}
		}
		return false;
	}
}
